package com.gg.registration.order.controller;

import com.gg.common.result.CommonResult;
import com.gg.common.result.ResultCodeEnum;
import com.gg.common.utils.RegistrationException;
import com.gg.registration.enums.PaymentStatusEnum;
import com.gg.registration.enums.PaymentTypeEnum;
import com.gg.registration.order.service.PaymentInfoService;
import com.gg.registration.order.service.WechatPayService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付调用的Controller
 *
 * Author：  chenjunjia
 * Date：    2022/4/27 21:23
 * WeChat：  China_JoJo_
 */
@RestController
@RequestMapping(value = "/api/order/weixin")
public class WechatPayController {

    @Resource
    private WechatPayService wechatPayService;

    @Resource
    private PaymentInfoService paymentInfoService;

    /**
     * 生成二维码所需参数的接口
     * @param orderId 订单号
     * @return
     */
    @GetMapping("createNative/{orderId}")
    public CommonResult createNative(@PathVariable("orderId") Long orderId) {
        if (null==orderId) {
            throw new RegistrationException("订单编号为空！",201);
        }
        Map resultMap = wechatPayService.createNative(orderId);
        if (null==resultMap) throw new RegistrationException("生成失败！",201);
        return new CommonResult(ResultCodeEnum.SUCCESS,resultMap);
    }

    /**
     * 查询支付状态的接口
     * @param orderId 订单号
     * @return
     * @throws Exception
     */
    @GetMapping("queryPayStatus/{orderId}")
    public CommonResult queryPayStatus(@PathVariable("orderId") Long orderId) throws Exception {
        System.out.println(orderId);
        if (null==orderId) {
            throw new RegistrationException("订单编号为空！",201);
        }
        //根据订单编号、支付类型，调用微信支付接口查询
        Map<String,String> resultMap = wechatPayService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.getStatus());
        if (null == resultMap) {
            return new CommonResult(ResultCodeEnum.FAIL,"获取不到orderid与支付状态对应的消费记录");
        }
        //当扫码支付完成后，微信那边会把这个 "trade_state" 属性改成SUCCESS
        //若未支付，则这个属性是：NOTPAY，在返回的 xml 里可以看见
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            String outTradeNo = resultMap.get("out_trade_no");
            //更改订单状态
            //删除redis的key(paymentInfoService中完成)
            paymentInfoService.paySuccess(outTradeNo,PaymentTypeEnum.WEIXIN.getStatus(),resultMap);
            return new CommonResult(ResultCodeEnum.SUCCESS,"支付成功");
        }
        return new CommonResult(ResultCodeEnum.SUCCESS,"支付中");
    }
}
